<template>
  <div>
    <div v-if="!img" class="upload-img-box" :style="{ height: HEIGHT + 'px', width: WIDTH + 'px' }" @click="showDialog">
      <i class="el-icon-plus"></i>
    </div>
    <div v-else class="preview-img-box" :style="{ height: HEIGHT + 'px', width: WIDTH + 'px' }" @click="showDialog">
      <el-button type="danger" icon="el-icon-close" circle @click.stop="removeImg"></el-button>
      <el-image :src="imgUrl + img" fit="cover"></el-image>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  /**
   * UploadImg 图片上传
   * @description 本组件一般用于图片选择及预览占位。
   * @property {String Number} height 组件高度，可以为字符串或者数值，单位px（默认60）
   * @property {String Number} width 组件宽度，可以为字符串或者数值，单位px（默认60）
   * @property {String Number} size 组件尺寸，宽高一致时的省略写法。可以为字符串或者数值，单位rpx（默认0），如果设置了尺寸则宽高失效
   * @property {String} img 父子组件双向绑定的图片地址
   * @property {String} index 用户传递的标识符值，如果是列表循环，可传v-for的index值
   * @event {Function} click 组件被点击
   * @event {Function} remove 删除图标被点击
   * @example <upload-img v-model="scope.row.img" size="80" @click="showImgManager" :index="scope.$index"></upload-img>
   */
  name: 'UploadImg',
  props: {
    height: {
      type: [Number, String],
      default: 60,
    },
    width: {
      type: [Number, String],
      default: 60,
    },
    size: {
      type: [Number, String],
      default: 0,
    },
    img: {
      type: String,
      default: '',
    },
    index: {
      type: [Number, String],
      default: 0,
    },
  },
  model: {
    prop: 'img',
    event: 'change',
  },
  data() {
    return {
      HEIGHT: '',
      WIDTH: '',
    }
  },
  created() {
    this.HEIGHT = this.size ? this.size : this.height
    this.WIDTH = this.size ? this.size : this.width
  },
  methods: {
    showDialog() {
      this.$emit('click', this.index)
    },
    removeImg() {
      this.$emit('remove', this.index)
    },
    handleChange(event) {
      this.$emit('change', event)
    },
  },
  computed: {
    ...mapGetters({
      imgUrl: 'settings/imgUrl',
    }),
  },
}
</script>

<style lang="scss" scoped>
.upload-img-box {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 0;
  padding: 0;
  height: 100px;
  width: 100px;
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
  border-radius: 6px;
  cursor: pointer;
  &:hover {
    border-color: #409eff;
    color: #409eff;
  }
  i {
    font-size: 28px;
    color: #a0a6ad;
    &:hover {
      opacity: 1;
    }
  }
}
.preview-img-box {
  position: relative;
  ::v-deep .el-button {
    position: absolute;
    right: 0;
    top: 0;
    transform: translate(50%, -50%);
    padding: 3px;
    opacity: 0;
    z-index: 1;
  }
  .el-image {
    width: 100% !important;
    height: 100% !important;
    max-width: 100%;
    max-height: 100%;
    border-radius: 6px;
    cursor: pointer;
  }
  &:hover {
    .el-button {
      opacity: 1;
    }
  }
}
</style>
